package com.ruoyi.system.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.enums.LivePlayBackEvenNameEnum;
import com.ruoyi.common.core.utils.Helper;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.redis.service.RedisService;
import com.ruoyi.system.domain.BaseContest;
import com.ruoyi.system.domain.BaseLiveTournament;
import com.ruoyi.system.domain.BaseTournament;
import com.ruoyi.system.domain.LiveMessageCode;
import com.ruoyi.system.domain.dto.CreateLiveWatermarkRuleDto;
import com.ruoyi.system.domain.vo.BaseTournamentResponseVO;
import com.ruoyi.system.mapper.BaseTournamentMapper;
import com.ruoyi.system.service.IBaseContestService;
import com.ruoyi.system.service.IBaseLivePlayBackEvenService;
import com.ruoyi.system.service.IBaseTournamentService;
import com.ruoyi.system.service.impl.BaseLiveTournamentServiceImpl;
import com.ruoyi.system.service.impl.LiveService;
import com.ruoyi.system.service.impl.WebSocketServer;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.live.v20180801.models.SwitchBackupStreamRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;

@RestController
@RequestMapping("/wx/live")
@RequiredArgsConstructor
public class WxLiveController {

    private final Log logger = LogFactory.getLog(WxLiveController.class);

    private final LiveService liveService;

    private final WebSocketServer webSocketServer;

    @Resource
    BaseLiveTournamentServiceImpl baseLiveTournamentService;
    @Resource
    private IBaseLivePlayBackEvenService iBaseLivePlayBackEvenService;
    @Resource
    private RedisService redisService;
    @Resource
    private IBaseTournamentService baseTournamentService;
    @Resource
    private IBaseContestService baseContestService;
    /**
     * 腾讯云直播回调事件
     *
     * @param eventType
     * @param map
     * @return
     */
    @PostMapping("/callback/{eventType}")
    public Object callback(@PathVariable Integer eventType, @RequestBody HashMap<String, Object> map) {
        logger.info("进行了直播断流回调,回调参数为 : " + eventType);
        try {
            String streamName = (String) map.get("stream_id");
            switch (eventType) {
                case 0:
                    // 直播断流回调
                    logger.info("进行了直播断流回调,回调参数为 : " + map);
                    BaseLiveTournament baseLive = baseLiveTournamentService.getBaseLiveTournament(streamName);
                    //更改为y已关闭
                    baseLive.setState(2);
                    baseLiveTournamentService.updateById(baseLive);
////                    wxLiveRoomService.endLive(streamName); // 进行直播结束操作
//                    if(liveRoom.getStatus() == -1){
                        webSocketServer.sendMessageByCode(baseLive.getRoomNumber(), LiveMessageCode.LIVE_END,"直播已结束"); // 发送消息
//                    }else if(liveRoom.getStatus() == 2){
//                        webSocketServer.sendMessageByCode(liveRoom.getId(),LiveMessageCode.LIVE_TEMPORARILY_LEAVE,"主播暂时离开"); // 发送消息
//                    }
                    break;
                case 1:
                    // 直播推流回调
                    logger.info("进行了直播推流回调,回调参数为 : " + map);

                    String liveStr = redisService.getCacheObject(streamName);
                    BaseLiveTournament baseLiveTournament = JSON.parseObject(liveStr, BaseLiveTournament.class);
                    logger.info("直播推流回调缓存->>>"+JSON.toJSONString(baseLiveTournament));
                    baseLiveTournament.setState(1);
//                    BaseLiveTournament baseLiveTournament = baseLiveTournamentService.getBaseLiveTournament(streamName);
                    baseLiveTournamentService.insertBaseLiveTournament(baseLiveTournament);

                    HashMap<String, Object> messageMap = new HashMap<>();

                    messageMap.put("type", 0);
                    messageMap.put("message", "直播开始");

                    webSocketServer.sendMessageByCode(baseLiveTournament.getRoomNumber(), LiveMessageCode.LIVE_START, JSON.toJSONString(messageMap)); // 直播开始 发送消息
//                    }
                    //1开启水印
                    // 直播回调开启水印 并且合流
                    // 有比分变动 先修改水印 再合流
                    //比赛断流 进行水印删除

                    Long watermarkId = 0L;
                    BaseTournament tournament = baseTournamentService.selectBaseTournamentById(baseLiveTournament.getTournamentId());
                    logger.info("比赛数据"+JSON.toJSONString(tournament));
                    if (Objects.nonNull(tournament) && Objects.equals(tournament.getEquipmentSwitch(),1)){
//                        String subsection;
//                        if (Objects.equals(tournament.getSubsection(),1L)){
//                            subsection = "1st";
//                        }else if (Objects.equals(tournament.getSubsection(),2L)){
//                            subsection = "2nd";
//                        }else if (Objects.equals(tournament.getSubsection(),3L)){
//                            subsection = "3rd";
//                        }else{
//                            subsection = tournament.getSubsection()+"th";
//                        }
                        BaseContest contest = baseContestService.getById(tournament.getContestId());
//                        //添加比分栏水印
//                        watermarkId = liveService.addLiveWatermark(tournament.getTeamOneName(),tournament.getTeamOneScore(),subsection,
//                                tournament.getTeamTwoScore(),tournament.getTeamTwoName(),contest.getContestName(),0,0);
                        //添加联赛水印
                        if (Objects.equals(contest.getIsLogo(),1) && StringUtils.isNoneBlank(contest.getLogo())){
                            String logo = "https://boyubasketball.oss-cn-shanghai.aliyuncs.com/" + contest.getLogo();
                            Long aLong = liveService.addContestLiveWatermark(logo, contest.getContestName());
                            contest.setWatermarkId(aLong);
                            baseContestService.updateById(contest);
                            liveService.createCommonMixStream(streamName,watermarkId,contest.getWatermarkId());
                        }
                    }
                    BaseLiveTournament baseLiveTournament1 = new BaseLiveTournament();
                    baseLiveTournament1.setId(baseLiveTournament.getId());
                    baseLiveTournament1.setWatermarkId(watermarkId);
                    baseLiveTournamentService.updateById(baseLiveTournament1);
                    logger.info("进行了直播推流回调成功~");
                    break;
                case 100:
                    // 直播录制回调 存储录制地址到响应的动态直播间中
                    logger.info("进行了直播录制回调,回调参数为 : " + map);
                    BaseLiveTournament liveTournament = baseLiveTournamentService.getBaseLiveTournament(streamName);
                    Long tournamentId = liveTournament.getTournamentId();
                    String videoUrl = (String) map.get("video_url");
                    iBaseLivePlayBackEvenService.playbackEvent(LivePlayBackEvenNameEnum.LIVE_REPLAY.getName(),tournamentId,videoUrl,liveTournament.getType());

                    //断开混流 删除水印
                    if (Objects.nonNull(liveTournament.getWatermarkId()) && !Objects.equals(liveTournament.getWatermarkId(),0L)){
                        liveService.cancelCommonMixStream(streamName+"_room");
//                        liveService.deleteLiveWatermark(liveTournament.getWatermarkId());
//                        liveTournament.setWatermarkId(0L);
//                        baseLiveTournamentService.updateById(liveTournament);

                        BaseTournament byId = baseTournamentService.getById(liveTournament.getTournamentId());
                        BaseContest contest = baseContestService.getById(byId.getContestId());
                        if (!Objects.equals(contest.getWatermarkId(),0L)){
                            liveService.deleteLiveWatermark(contest.getWatermarkId());
                            contest.setWatermarkId(0L);
                            baseContestService.updateById(contest);
                        }

                    }
                    break;
                case 200:
                    // 直播截图事件回调
                    logger.info("进行了直播截图事件回调,回调参数为 : " + map);
                    break;
                case 317:
                    // 直播画面审核回调
                    logger.info("进行了直播画面审核回调,回调参数为 : " + map);
//                    wxLiveRoomService.frameExamine(map);
                    break;
                case 315:
                    // 直播音频审核回调
                    logger.info("进行了直播音频审核回调,回调参数为 : " + map);
                    break;
                case 321:
                    // 直播推流异常回调
                    logger.info("进行了直播推流异常回调,回调参数为 : " + map);
                    break;
                default:
                    return 1;
            }
            return 1;
        } catch (Exception e) {
            logger.error("直播回调出现异常... 回调事件类型为: " + eventType + " 回调参数为: " + map);
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取正在直播的流
     *
     * @return
     */
//    @GetMapping("/getDescribeLiveStream")
    public Object getDescribeLiveStream() {
        return liveService.describeLiveStreamPushInfoList();
    }

    /**
     * 查询流状态
     *
     * @param streamName
     * @return
     */
//    @GetMapping("describeLiveStreamState")
    public Object describeLiveStreamState(String streamName) {
        return liveService.describeLiveStreamState(streamName);
    }

    /**
     * 获取直播中的主备流
     *
     * @param streamName
     * @return
     * @throws TencentCloudSDKException
     */
//    @GetMapping("/getDescribeBackupStreamList")
    public Object getDescribeBackupStreamList(String streamName) throws TencentCloudSDKException {
        return liveService.describeBackupStreamList(streamName);
    }

    /**
     * 切换主备流
     *
     * @return
     */
//    @PostMapping("switchBackupStream")
    public Object switchBackupStream(@RequestBody SwitchBackupStreamRequest request) {
        return liveService.switchBackupStream(request.getStreamName(), request.getUpstreamSequence());
    }

    /**
     * 禁止直播推流
     *
     * @param streamName
     * @param seconds
     * @return
     */
//    @GetMapping("/forbidLiveStream")
    public Object forbidLiveStream(String streamName, Integer seconds) {
        return liveService.forbidLiveStream(streamName, seconds, "测试推送");
    }

    /**
     * 恢复直播推流
     *
     * @param streamName
     * @return
     */
//    @GetMapping("/resumeLiveStream")
    public Object resumeLiveStream(String streamName) {
        return liveService.resumeLiveStream(streamName);
    }

//    /**
//     * 身份鉴权认证
//
//     * @param token
//     * @return
//     */
//    @GetMapping("/authLiveUrl")
//    public Object authLiveUrl(String token) {
//        logger.info("token: " + token);
//        if (token != null && token.equals("1")) {
//            logger.error("身份验证成功...");
//            return ResponseUtil.ok();
//        }
//        logger.error("身份验证失败了...");
//        return new ResponseEntity<>("身份验证失败", HttpStatus.FORBIDDEN);
//    }

}
